package com.sky.demo03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 目标：演示synchronized不可中断
 * 1. 定义一个Runnable
 * 2. 在Runnable定义同步代码块
 * 3. 先开启一个线程来执行同步代码块，保证不退出同步代码块
 * 4. 后开启一个线程来执行同步代码块（阻塞状态）
 * 5. 停止第二个线程
 */
public class Test03interruptible {

    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        test02();

    }

    public static void test02() throws InterruptedException {
        Runnable run = () -> {
            String name = Thread.currentThread().getName();
            boolean b = false;
            try {
                b = lock.tryLock(3, TimeUnit.SECONDS);
                if (b) {
                    System.out.println(name + "获得锁，进入锁执行");
                    Thread.sleep(888888);
                } else {
                    System.out.println(name + "在指定时间内没有得到锁做其他操作");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                if (b) {
                    lock.unlock();
                    System.out.println(name + "释放锁");
                }
            }
        };

        Thread t1 = new Thread(run);
        t1.start();
        Thread.sleep(1000);
        Thread t2 = new Thread(run);
        t2.start();

//        System.out.println("停止t2线程前");
//        t2.interrupt();
//        System.out.println("停止t2线程后");
//
//        Thread.sleep(1000);
//
//        System.out.println(t1.getName() + t1.getState());
//        System.out.println(t2.getName() + t2.getState());

    }

    public static void test01() throws InterruptedException {
        Runnable run = () -> {
            String name = Thread.currentThread().getName();
            try {
                lock.lock();
                System.out.println(name + "获得锁，进入锁执行");
                Thread.sleep(888888);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
                System.out.println(name + "释放锁");
            }
        };

        Thread t1 = new Thread(run);
        t1.start();
        Thread.sleep(1000);
        Thread t2 = new Thread(run);
        t2.start();

        System.out.println("停止t2线程前");
        t2.interrupt();
        System.out.println("停止t2线程后");

        Thread.sleep(1000);

        System.out.println(t1.getName() + t1.getState());
        System.out.println(t2.getName() + t2.getState());

    }

}
